// pages/discovery//relevance/relevance.js
const util = require('../../../utils/util')
const app = getApp();
import { articleSave } from '../../../api/article'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    APP_OSSURL_API: app.APP_OSSURL_API,
    yjtImageUrl: "/dinnerBar/lvyou/lvyou-gengduo.png",
    travelImageUrl: "/dinnerBar/lvyou/meizhoudao.jpg",
    closeImageUrl: "/dinnerBar/dingdan/dingdan-genzong-x.png",
    pingfenredImageUrl: "/dinnerBar/canyin/canyin-pingfen-red.png",
    pingfengrayImageUrl: "/dinnerBar/canyin/canyin-pingfen-gray.png",
    zhaopianImageUrl: "/dinnerBar/fabu/zhaopian.png",
    shipinImageUrl: "/dinnerBar/fabu/shipin.png",
    jiahaoImageUrl: "/dinnerBar/fabu/jiahao.jpg",

    enableUpload: true,
    articleContent: '',
    relavances: [],
    showTypeMenu: false,
  },
  /**
   * 点击取消按钮
   */
  cancel: function () {
    wx.navigateBack({
      delta: 1,
    })
  },
  /**
   * 点击保存按钮
   */
  save: function () {
    // unknow TODO
    wx.showToast({
      title: '保存成功',
    })
  },

  /**
   * 发布，图片/视频上传成功后回调函数
   * @param {图片/视频访问路径}} e 
   */
  uploaded: function (e) {
    //检验必填项是否为空，TODO，后续更改为在上传图片之前
    let _articleContent = this.data.articleContent
    if (!_articleContent.length) {
      wx.showToast({ icon: 'none', title: '内容为必填项' })
      return
    }
    this.setData({
      "article.articleMeta": { images: e.detail.images, video: e.detail.video },
      "article.content": _articleContent,
      "article.articleType": 2,
      "article.title": _articleContent.substr(0, 10) + (_articleContent.length > 10 ? '...' : ''),
      "article.subTitle": _articleContent.substr(0, 10) + (_articleContent.length > 10 ? '...' : ''),
      "article.thumbnail": e.detail.thumbSrc[0],
      "article.productId": (this.data.relavances.length && this.data.relavances[0].id) || NaN
    })
    articleSave(this.data.article).then(res => {
      if (res.type === 'success') {
        wx.showToast({
          title: '发布成功',
          duration:500
        })
        setTimeout(()=>{
          debugger
          wx.navigateTo({
            url: `/pages/member/follow/dynamic/index?id=${res.data.talentId}`,
          })
        },600)
      } else {
        wx.showToast({
          title: '发布失败',
        })
      }
    })
  },

  /**
   * 上传图片
   */
  chooseImg: function () {
    let _filePaths = this.data.uploadFiles.filePaths
    wx.chooseImage({
      count: 9 - _filePaths.length || 0, //
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (res) => {
        // console.log(res)
        this.setData({
          'uploadFiles.type': 'img',
          'uploadFiles.filePaths': [..._filePaths, ...res.tempFilePaths],
          'enableUpload': !((_filePaths.length + res.tempFilePaths.length) >= 9),
        })
        if (!this.data.uploadFiles.thumbSrc) {
          this.setData({
            'uploadFiles.thumbSrc': res.tempFilePaths[0],
          })
        }
      }
    })
  },

  /**
   * 上传视频
   */
  chooseVideo: function () {
    let _filePaths = this.data.uploadFiles.filePaths
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: (res) => {
        this.setData({
          'uploadFiles.type': 'video',
          'uploadFiles.filePaths': [..._filePaths, res.tempFilePath],
          'enableUpload': false
        })
        if (!this.data.uploadFiles.thumbSrc) {
          this.setData({
            'uploadFiles.thumbSrc': res.thumbTempFilePath,
          })
        }
      }
    })
  },

  /**
   * 删除图片/视频
   */
  deleteFile: function (e) {
    let i = e.currentTarget.dataset.index
    let _filePaths = this.data.uploadFiles.filePaths
    _filePaths.splice(i, 1)
    this.setData({
      "uploadFiles.filePaths": _filePaths,
      "uploadFiles.thumbSrc": _filePaths[0],
      enableUpload: true
    })
    if (_filePaths.length == 0) {
      this.setData({
        "uploadFiles.thumbSrc": ""
      })
    }
  },

  /**
   * 预览图片/视频
   */
  previewMedia: function (e) {
    let _uploadFiles = this.data.uploadFiles
    wx.previewMedia({
      sources: _uploadFiles.filePaths.map(e => {
        return {
          url: e,
          type: _uploadFiles.type == "img" ? "image" : "video"
        }
      }),
      current: e.currentTarget.dataset.index
    })
  },

  /**
   * 跳转到关联页面选择关联店铺/景点
   */
  toRelevance: function () {
    wx.navigateTo({
      url: '/pages/discovery/relevance/relevance',
      events: {
        getRelevanceData: e => {
          this.setData({
            relavances: [e.relavance]
          })
          // this.setData({
          //   relavances:[...this.data.relavances,e.relavance]
          // })
        }
      }
    })
  },
  cancelRelavance: function () {
    this.setData({
      relavances: []
    })
  },

  starIt: function (e) {
    // 暂无
    console.log(e.currentTarget.dataset.index)
  },
  showMenu: function () {
    this.setData({
      showTypeMenu: true
    })
  },
  cancelMenu: function () {
    this.setData({
      showTypeMenu: false
    })
  },
  toShoot: function (e) {
    wx.navigateTo({
      url: `../shoot/shoot?type=${e.currentTarget.dataset.type}`,
      events: {
        getMedia: this.getMedia
      }
    })
  },
  getMedia: function ({ type, filePath, thumbSrc }) {
    this.setData({
      uploadFiles: {
        type: type, // || 'img'
        filePaths: filePath ? [filePath] : [],
        thumbSrc: thumbSrc
      },
      article: {
        address: app.globalData.address,
        areaId: app.globalData.areaId,
        articleMeta: {},
        articleType: 2,
        // author: app.globalData.userInfo.name||"测试用户",
        content: "",
        lat: app.globalData.lat,
        lng: app.globalData.lng,
        mediaType: 0,//媒体类型 {0:图文,1:视频}
        productId: NaN,
        subTitle: '',
        // talentId: app.globalData.userInfo.id||'1',
        thumbnail: '',
        title: '',
      },
      enableUpload: type == 'img',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({ type, filePath, thumbSrc }) {
    console.log(app.globalData)
    this.setData({
      uploadFiles: {
        filePaths: []
      },
      enableUpload: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})